<?php

class PasswdForm extends CFormModel
{
	public $passwdOld;
	public $passwdNew;
	public $passwdAgain;
	private $_user;

	public function rules()
	{
		return array(
			array('passwdOld, passwdNew,passwdAgain', 'required'),
			array('passwdOld', 'authenticate'),
			array('passwdAgain','compare','compareAttribute'=>'passwdNew'),
		);
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels()
	{
		return array(
			'passwdOld'=>Yii::t('users','passwd old'),
			'passwdNew'=>Yii::t('users','passwd new'),
			'passwdAgain'=>Yii::t('users','passwd again'),
		);
	}

	/**
	 * Authenticates the password.
	 * This is the 'authenticate' validator as declared in rules().
	 */
	public function authenticate($attribute,$params)
	{
		if(!$this->hasErrors())
		{
			$user = $this->_getUser();
			if(!$user || !$user->validatePassword($this->passwdOld))
				$this->addError('passwdOld',Yii::t('users', 'incorrect password'));
		}
	}
	
	public function changePasswd(){
		$user = $this->_getUser();
		$user->password = $this->passwdNew;
		$user->save();
	}
	
	private function _getUser(){
		if($this->_user == null)
			$this->_user = User::model()->find('LOWER(username)=?' ,array(strtolower(Yii::app()->user->name)));
		return $this->_user;
	}

}
